
package devbureau.fstore.common.db;

import devbureau.fstore.common.OrderLine;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.apache.log4j.Logger;

public class CreateOrderLineAction {

  	private static Logger logger = Logger.getLogger(CreateOrderLineAction.class);

	public static final String NEXT_ORDER_LINE = "values nextval for STORE.ORDER_LINE_SEQ";
    public static final String INSERT_ORDER_LINE = "insert into STORE.ORDER_LINE(ID,ORDER_ID,ITEM_ID,QUANTITY,PRICE_RUR) values (?,?,?,?,?)";
    public static final String UPDATE_ITEM_BALANCE = "update STORE.ITEM set BALANCE = (BALANCE - ?), MODIFIED = CURRENT_TIMESTAMP where ID = ?";

    private Integer lineId = null;

    public CreateOrderLineAction() {
    }

    protected void execute(Connection connection,Integer orderId,OrderLine line)throws Exception{

        PreparedStatement psNextId =null;
        ResultSet rsNextId  = null;
        PreparedStatement ps = null;

        logger.info("#run line : " + line);
        ps = connection.prepareStatement(UPDATE_ITEM_BALANCE);

        ps.setInt(1, line.getQuantity());
        ps.setInt(2, line.getItemId());

        ps.executeUpdate();
        ps.close();

        logger.info("#run update OK");

        // next order line id
        Integer orderLineId = null;
        psNextId = connection.prepareStatement(NEXT_ORDER_LINE);
        rsNextId  = psNextId.executeQuery();
        if(rsNextId.next()){
            orderLineId = rsNextId.getInt(1);
            lineId = orderLineId;
        }
        rsNextId.close();
        psNextId.close();

        // insert order items
        ps = connection.prepareStatement(INSERT_ORDER_LINE);

        ps.setInt(1, orderLineId);
        ps.setInt(2, orderId);
        ps.setInt(3, line.getItemId());
        ps.setInt(4, line.getQuantity());
        ps.setDouble(5,line.getPrice());

        ps.executeUpdate();
        ps.close();

    }

    public Integer getLineId(){
        return lineId;
    }


}
